//
//  TxLivePlayView.m
//  cryptox
//
//  Created by FXY on 2022/6/26.
//

#import "TxLivePlayView.h"

#import <TXLiteAVSDK_Professional/TXVodPlayer.h>
#import <TXLiteAVSDK_Professional/TXPlayerGlobalSetting.h>

typedef enum : NSInteger {
    TxLivePlayStatusStart,
    TxLivePlayStatusRun,
    TxLivePlayStatusPause,
} TxLivePlayStatus;

@interface TxLivePlayView () <TXVodPlayListener, TXVideoCustomProcessDelegate>

@property (strong ,nonatomic) TXVodPlayConfig *txLivePlayConfig;
@property (strong ,nonatomic) TXVodPlayer *txLivePlayer;

@property (strong, nonatomic) NSArray *playUrls;
@property (copy, nonatomic) NSString *cacheFilePath;

@property (assign, nonatomic) NSInteger currentIndex;

@property (assign, nonatomic) BOOL isPlaying;

@property (assign, nonatomic) TxLivePlayStatus playStatus;

@end

@implementation TxLivePlayView

- (TXVodPlayConfig *)txLivePlayConfig{
    if (!_txLivePlayConfig) {
        _txLivePlayConfig = [[TXVodPlayConfig alloc] init];
    }
    
    return _txLivePlayConfig;
}

- (TXVodPlayer *)txLivePlayer{
    if (!_txLivePlayer) {
        _txLivePlayer = [[TXVodPlayer alloc] init];
        [_txLivePlayer setConfig:self.txLivePlayConfig];
        _txLivePlayer.vodDelegate = self;
        
    }
    return _txLivePlayer;
}

- (instancetype)initWithFrame:(CGRect)frame args:(NSDictionary *)args{
    if (self = [super initWithFrame:frame]) {
        [self configData];
    }
    
    return self;
}

/// 基本配置
- (void)configData{
    [self.txLivePlayer setupVideoWidget:self insertIndex:0];
}

#pragma mark - TXVodPlayListener
- (void)onPlayEvent:(TXVodPlayer *)player event:(int)EvtID withParam:(NSDictionary *)param{

    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (EvtID == PLAY_EVT_PLAY_BEGIN) {
            [self stopLoadingAnimation];
        } else if (EvtID == PLAY_EVT_RCV_FIRST_I_FRAME) {
            [self stopLoadingAnimation];
        } else if (EvtID == PLAY_EVT_PLAY_PROGRESS) {
            NSInteger progress = [param[EVT_PLAY_PROGRESS] floatValue]*1000;
            NSInteger duration = [param[EVT_PLAY_DURATION] floatValue]*1000;
            NSInteger playable = [param[EVT_PLAYABLE_DURATION] floatValue]*1000;
            
            NSDictionary *mData = @{
                @"progress":@(progress),
                @"duration":@(duration),
                @"playable":@(playable),
                @"startTime":[self getFormatDuration:progress / 1000],
                @"durationTime":[self getFormatDuration:duration / 1000],
            };
            
            if (self.callBlock) {
                self.callBlock(@"playProcess", mData);
            }
            
        } else if (EvtID == PLAY_ERR_NET_DISCONNECT||EvtID == PLAY_EVT_PLAY_END||EvtID == PLAY_ERR_FILE_NOT_FOUND) {
            [self stopPlayRtmp];
            
            // 自动播放下一个
            if (self.callBlock) {
                self.callBlock(@"playProcess", @{@"progress":@(0)});
            }
            
            self.currentIndex++;
            if (self.currentIndex <self.playUrls.count) {
                [self.txLivePlayer startVodPlay:self.playUrls[self.currentIndex]];
//                [self.txLivePlayer startPlay:self.playUrls[self.currentIndex]];
                if (self.callBlock) {
                    self.callBlock(@"toast", @"播放证据的下一个视频");
                }
            } else if (self.currentIndex == self.playUrls.count) {
                // 播放结束
                if (self.callBlock) {
                    self.callBlock(@"toast", @"播放结束");
                }
            } else {
                self.currentIndex = 0;
            }
        } else if (EvtID == PLAY_WARNING_RECONNECT) {
            [self startLoadingAnimation];
        } else if (EvtID == PLAY_ERR_HLS_KEY) {
            [self stopPlayRtmp];
        }
        
    });
    
}

- (void)onNetStatus:(TXVodPlayer *)player withParam:(NSDictionary *)param{

}

#pragma mark - flutter事件
- (void)startPlay:(NSDictionary *)dic{
    if (dic!=nil&&[dic isKindOfClass:NSDictionary.class]) {
        NSArray *urls = NSArray.array;
        NSString *cacheFilePath = @"";
        if ([dic.allKeys containsObject:@"urls"]) {
            urls = [dic valueForKey:@"urls"];
        }
        if ([dic.allKeys containsObject:@"cacheFilePath"]) {
            cacheFilePath = [dic valueForKey:@"cacheFilePath"];
        }
        
        self.playUrls = urls;
        self.cacheFilePath = cacheFilePath;
        
//        self.txLivePlayConfig.cacheFolderPath = cacheFilePath;
        
        [TXPlayerGlobalSetting setCacheFolderPath:cacheFilePath];
        
        [self.txLivePlayer setConfig:self.txLivePlayConfig];
        
        if (self.playStatus!=TxLivePlayStatusStart) {
            if (!self.txLivePlayer.isPlaying) {
                [self.txLivePlayer resume];
                self.playStatus = TxLivePlayStatusRun;
            } else {
                [self.txLivePlayer pause];
                self.playStatus = TxLivePlayStatusPause;
            }
            [self callBlackPlayingStatus];
        } else {
            [self firstPlayRtmp];
        }
    }
    
}

- (void)stopPlay{
    [self stopPlayRtmp];
}

- (void)onPause{
    [self.txLivePlayer pause];
    self.playStatus = TxLivePlayStatusPause;
    
    [self callBlackPlayingStatus];
}

- (void)onResume{
    [self.txLivePlayer resume];
    self.playStatus = TxLivePlayStatusStart;
    
    [self callBlackPlayingStatus];
}

- (void)onDestroy{
    [self.txLivePlayer stopPlay];
}

- (void)firstPlayRtmp{
    if (self.playUrls==nil||self.playUrls.count==0) {
        return;
    }
    self.currentIndex = 0;
    self.playStatus = TxLivePlayStatusRun;
    [self startPlayRtmp:self.playUrls.firstObject];
}

- (void)startPlayRtmp:(NSString *)playUrl{
    NSInteger result = [self.txLivePlayer startVodPlay:playUrl];
    if (result!=0) {
        self.playStatus = TxLivePlayStatusRun;
        [self callBlackPlayingStatus];
        
        if (self.callBlock) {
            self.callBlock(@"startPlay", [NSNumber numberWithBool:NO]);
        }
        return;
    }
    
    [self startLoadingAnimation];
    
    if (self.callBlock) {
        self.callBlock(@"startPlay", [NSNumber numberWithBool:YES]);
    }
    
    self.playStatus = TxLivePlayStatusRun;
    [self callBlackPlayingStatus];
}

- (void)startLoadingAnimation{
    if (self.callBlock) {
        self.callBlock(@"startLoading", [NSNumber numberWithBool:YES]);
    }
}

- (void)stopLoadingAnimation{
    if (self.callBlock) {
        self.callBlock(@"startLoading", [NSNumber numberWithBool:false]);
    }
}

- (BOOL)isPlaying{
    return self.txLivePlayer.isPlaying||self.playStatus==TxLivePlayStatusRun;
}

- (void)stopPlayRtmp{
    [self stopLoadingAnimation];
    
    [self.txLivePlayer stopPlay];
    
    self.playStatus = TxLivePlayStatusStart;
    [self callBlackPlayingStatus];
}


- (void)seek:(NSDictionary *)dic{
    if (dic!=nil&&[dic isKindOfClass:NSDictionary.class]) {
        NSInteger progress = 0;
        if ([dic.allKeys containsObject:@"progress"]) {
            progress = [[dic valueForKey:@"progress"] intValue];
        }
        [self.txLivePlayer seek:progress];
    }
}

/// 0 - 开始，1-播放中，2-暂停
- (void)callBlackPlayingStatus{
    if (self.callBlock) {
        self.callBlock(@"playStatus", @(self.playStatus));
    }
}

/// 将指定的秒数转换成00:00:00格式时间，例如：65转换后为00:01:05
- (NSString *)getFormatDuration:(NSInteger)duration{
    NSInteger time = duration % 3600;
    NSInteger hour = duration / 3600;
    NSInteger minute = time / 60;
    NSInteger second = time % 60;
    
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minute,second];
}

@end
